//
//  RadioPlayViewController.m
//  Leisure
//
//  Created by 大展 on 16/7/5.
//  Copyright © 2016年 大展. All rights reserved.
//

#import "RadioPlayViewController.h"

@interface RadioPlayViewController ()<UITableViewDelegate,UITableViewDataSource,PlayManagerDelegate,UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *coverimg;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic,assign)NSInteger currentIndex; // 当前正在播放的下标
@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;

@property (nonatomic, strong)UIView *greenView;

@end

@implementation RadioPlayViewController

// 下载事件
- (IBAction)downloadAction:(id)sender {


    if ([[CoreDataManager defaultManager] isContainDownloadModelWithUrl:[self.dataSource[self.currentIndex] musicUrl]]) {


        return;
    }

    Download *download = [[DownloadManager sharedManager] findDownloadWithUrl:[self.dataSource[self.currentIndex] musicUrl]];

    if (!download) {

       download = [[DownloadManager sharedManager]addDownloadWithUrl:[self.dataSource[self.currentIndex] musicUrl]];
        [download startDownload];

        [self setPlayInfoWithIndex:self.currentIndex];
    }

    NSLog(@"已经下载");

}

// 根据下标找到对应的cell
- (UITableViewCell *)fetchCellWithIndex:(NSInteger)index {

    return [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}

- (UIView *)greenView {

    if (!_greenView) {

        _greenView = [[UIView alloc]initWithFrame:CGRectMake(kWidth-10, 0, 10, [self fetchCellWithIndex:0].frame.size.height)];
        _greenView.backgroundColor = [UIColor greenColor];
    }
    return _greenView;
}

// 重写dataSource的set方法
- (void)setDataSource:(NSArray *)dataSource {

    if (_dataSource[0] != dataSource[0]) {

        self.currentIndex = -1;
        _dataSource = dataSource;
    }
}

// 单例
+ (instancetype)sharedManager {

    static RadioPlayViewController *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        handle = [[RadioPlayViewController alloc]initWithNibName:@"RadioPlayViewController" bundle:nil];
    });
    return handle;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.currentIndex = -1;
    [PlayManager sharedManager].delegate = self;
    self.webView.delegate = self;


    // 设置WebView
    [self.webView.scrollView.subviews[0] setValue:[UIColor redColor] forKey:@"backgroundColor"];
    self.webView.opaque = NO;
    self.webView.backgroundColor = [UIColor clearColor];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

      [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FF0000'"];
}

// 视图将要出现
- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    // 为了防止点击同一首重新播放的情况发生
    if (self.index != self.currentIndex) {

        self.currentIndex = self.index;
        [self setPlayInfoWithIndex:self.currentIndex];
    }
}

// 滑块
- (IBAction)sliderAction:(UISlider *)sender {

    [[PlayManager sharedManager] playMusicWithSliderValue:sender.value];
}

// 上一首
- (IBAction)playLastOne:(id)sender {

    if (self.currentIndex == 0) {

        self.currentIndex = self.dataSource.count-1;
    } else {

        self.currentIndex--;
    }
    [self setPlayInfoWithIndex:self.currentIndex];

}

//播放暂停
- (IBAction)playOrPause:(id)sender {

    if ([[PlayManager sharedManager]isPlaying]) {

        [[PlayManager sharedManager]pauseMusic];
    }else{

        [[PlayManager sharedManager]playMusic];
    }
}

// 下一首
- (IBAction)playNextOne:(id)sender {

    if (self.currentIndex == self.dataSource.count -1) {

        self.currentIndex = 0;
    }else {

        self.currentIndex++;
    }
    [self setPlayInfoWithIndex:self.currentIndex];
}

// 设置界面信息
- (void)setPlayInfoWithIndex:(NSInteger)index {

    RadioDetailModel *model = self.dataSource[index];

    // 子线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        // 播放音乐
        [[PlayManager sharedManager]prepareToPlayMusicWithUrl:model.musicUrl];
        // 加载网页
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.webview_url]]];

        // 主线程
        dispatch_async(dispatch_get_main_queue(), ^{

            [self.tableView reloadData];
            self.title = model.title;
            [self.coverimg sd_setImageWithURL:[NSURL URLWithString:model.imgUrl]];
            [self.greenView removeFromSuperview];
            [[self fetchCellWithIndex:index].contentView addSubview:self.greenView];


            Download *download = [[DownloadManager sharedManager] findDownloadWithUrl:model.musicUrl];

            if (download) {

                [download downloading:^(long long bytesWritten, float progress) {


                    NSLog(@"%f",progress);
                } didFinished:^(NSString *filePath, NSString *url) {

                    dispatch_async(dispatch_get_main_queue(), ^{

                        [self.downloadBtn setTitle:@"下载完成" forState:UIControlStateNormal];
                    });
                }];
                [self.downloadBtn setTitle:@"下载中" forState:UIControlStateNormal];
            } else {

                if ([[CoreDataManager defaultManager] isContainDownloadModelWithUrl:model.musicUrl]) {

                    [self.downloadBtn setTitle:@"下载完成" forState:UIControlStateNormal];
                } else{

                    [self.downloadBtn setTitle:@"下载" forState:UIControlStateNormal];
                }
            }
        });
    });
}

#pragma mark PlayManagerDelegate 

- (void)playManagerDelegateFetchTotalTime:(NSString *)totalTime currentTime:(NSString *)currentTime progress:(CGFloat)progress {
    self.slider.value = progress;
}

- (void)playToNextMusic {

    [self playNextOne:nil];
}

#pragma mark TableViewDelegate 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];

    cell.textLabel.text = [self.dataSource[indexPath.row] title];

    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
